package org.itboys.mobile.service.mongo.weixin;


import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mongo.ZhongBaoMessage;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.itboys.weixin.tools.WeiXinTemplateMessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：众包_微信_消息_service
 */
@Service
public class ZhongBaoWeiXinMessageService extends BaseMongoService<ZhongBaoMessage> {
    @Autowired
    private SundayWeiXinMemberService memberService;
    @Autowired
    private ZhongBaoWeiXinProjectService projectService;
    @Autowired
    private ResourceHolder resourceHolder;

    @Resource(name = "mobileDs")
    private MongoDataSource mobileDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return mobileDataSource;
    }

    @Override
    protected Class<ZhongBaoMessage> getEntityClass() {
        return ZhongBaoMessage.class;
    }


    /**
     * 分页获取消息
     * @param request
     * @param memberId
     * @param status
     * @param type
     * @return
     */
    public List<ZhongBaoMessage>  getMessage(HttpServletRequest request,Long memberId,Integer status,Integer type){
        Map<String,Object> param=ParamUtil.packageMongoExactParam(request,"projectId");
            param.put("type",type);
            param.put("status",status);
            param.put("memberId",memberId);
            Map<String,String> containsparam= ParamUtil.packageMongoVagueParam(request,"projectName","title");
        return super.containpageQuery(request,containsparam,param).getData();
    }



    /**
     *创建消息
     * @param memberId  消息接收人
     *  @param senderId 消息发送人
     * @param projectId
     * @param type
     * @param title
     * @param desc
     * @param otherId 关联业务对象ID
     */
    public void generateMessage(Long memberId,Long senderId,Long projectId,  Integer type,String title, String desc,Long otherId,Long needToReadMessageId) {
        //消息归属人
        SundayMember member=memberService.getById(memberId);
        //消息发送人
        SundayMember sender=memberService.getById(senderId);
        //项目是否为空
        String projectName="";
        if(LongUtil.isNotZreo(projectId)){
            projectName=projectService.getById(projectId).getName();
        }
      //  ZhongBaoProject project=projectService.getById(projectId);
       ZhongBaoMessage message= new ZhongBaoMessage(
                member.getId(), member.getNickName(), member.getMobile(),
                sender.getId(), sender.getNickName(), sender.getMobile(),
                projectId, projectName, title, desc, SundayCommonConstants.NO,
                type,otherId);
        super.save(message);
        //处理需要已读的mesg
        if(LongUtil.isNotZreo(needToReadMessageId)){
            super.update(needToReadMessageId,"status",SundayCommonConstants.YES);
        }
        //推送微信消息
     WeiXinTemplateMessageUtils.send(member.getWeixinOpenId(),member.getNickName(),title,message.getTypeStr(),"点击查看详情",resourceHolder.getStringValue("adminRoot")+"/sunday/weixin/safe/oAuth?type=5");
    }

    /**
     * 消息已读
     * @param messageId
     * @param messageIds
     */
   public void read(Long messageId,List<Long> messageIds){
       if(!LongUtil.isNotZreo(messageId)&&ListUtil.isNull(messageIds))return;
       Map<String,Object> param = new HashMap<String,Object>();
       param.put("isDeleted", SundayCommonConstants.NO);
       if(LongUtil.isNotZreo(messageId)){
           param.put("id",messageId);
       }
       if(ListUtil.isNotNull(messageIds)){
           param.put("id in",messageIds);
       }
       List<ZhongBaoMessage> messages=super.list(param);
        for(ZhongBaoMessage message:messages){
            message.setStatus(1);
        }
        if(ListUtil.isNull(messages))return;
       super.batchUpdateWithoutLogin(messages);

   }
    /**
     *
     */
    /**
     * 获取消息首页需要的未读消息统计信息
     * @param memberId
     * @return 1,项目审核类（含申请和申请结果），2，报名审核类（含申请和申请结果），3，留言类,4合计
     */
    public Map<String,Object> getIndexData(Long memberId){
        Map<String,Object> result = new HashMap<String,Object>();
        //项目审核类
        Integer projects = 0;
        //报名审核类
        Integer signs=0;
        //留言类型
        Integer words= 0;
        //合计
        Integer total=0;
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("status",SundayCommonConstants.NO);
        param.put("memberId",memberId);
        List<ZhongBaoMessage> messages = super.list(param);
        for(ZhongBaoMessage message:messages){

            if(message.getType()==SundayCommonConstants.zhongbao_message_type_apply||
                    message.getType()==SundayCommonConstants.zhongbao_message_type_refuse||
                    message.getType()==SundayCommonConstants.zhongbao_message_type_pass){
                projects++;
            }
            if(message.getType()==SundayCommonConstants.zhongbao_message_type_sign_apply||
                    message.getType()==SundayCommonConstants.zhongbao_message_type_sign_refuse||
                    message.getType()==SundayCommonConstants.zhongbao_message_type_sign_pass){
                signs++;
            }
            if(message.getType()==SundayCommonConstants.zhongbao_message_type_word){
                words++;
            }
        }
        result.put("projects",projects);
        result.put("signs",signs);
        result.put("words",words);
        total=projects+signs+words;
        result.put("total",total);
        return result;
    }

    /**
     * 分页获取消息通知。前端控制排序参数。默认将未读消息放到前面
     * @param request
     *  @param memberId

     * @return
     */
   /* public List<ZhongBaoMessage> getData(HttpServletRequest request,Long memberId ,Integer type,Integer status){
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("memberId",memberId);
        if(status!=null){
            param.put("status",SundayCommonConstants.NO);
        }

        if(type==1){
            param.put("type in",new Integer[]{
                    SundayCommonConstants.zhongbao_message_type_apply,
                    SundayCommonConstants.zhongbao_message_type_refuse,
                    SundayCommonConstants.zhongbao_message_type_pass,});
        }else if(type==2){
            param.put("type in",new Integer[]{
                    SundayCommonConstants.zhongbao_message_type_sign_apply,
                    SundayCommonConstants.zhongbao_message_type_sign_refuse,
                    SundayCommonConstants.zhongbao_message_type_sign_pass,});
        }else if(type==3){
            param.put("type in",new Integer[]{
                    SundayCommonConstants.zhongbao_message_type_word});
        }else{

        }
        Map<String,String> containsparam = ParamUtil.packageMongoVagueParam(request,"title","projectName");
        return super.containpageQuery(request,containsparam,param).getData();
    }*/
    /**
     *  获取消息通知。不获取留言类消息
     * @param request
     * @param memberId
     * @param status
     * @return
     */
    public List<ZhongBaoMessage> getData(HttpServletRequest request,Long memberId,Integer status){
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("memberId",memberId);
        //2017年12月22日，按照时间最近
       // param.put("sort","-ct,status");

        if(status!=null){
            param.put("status",SundayCommonConstants.NO);
        }
        param.put("type in",new Integer[]{
                SundayCommonConstants.zhongbao_message_type_apply,
                SundayCommonConstants.zhongbao_message_type_refuse,
                SundayCommonConstants.zhongbao_message_type_pass,
                SundayCommonConstants.zhongbao_message_type_sign_apply,
                SundayCommonConstants.zhongbao_message_type_sign_refuse,
                SundayCommonConstants.zhongbao_message_type_sign_pass,
                SundayCommonConstants.zhongbao_message_type_project,
                SundayCommonConstants.zhongbao_message_type_success});

        Map<String,String> containsparam = ParamUtil.packageMongoVagueParam(request,"title","projectName");
        PageResult<ZhongBaoMessage> pageResult=super.containpageQuery(request,containsparam,param);

        return pageResult.getData();
    }

    /**
     * 将消息转发给他人。只有项目审核消息或报名申请消息,2018年1月14日，废弃
     * @param messageId
     * @param memberId
     */
    public void change(Long messageId,Long memberId){
            ZhongBaoMessage message = super.getById(memberId);
            if(message.getStatus()==SundayCommonConstants.NO){
                message.setMemberId(memberId);
                super.updateExceptEmpty(messageId,message);

            }
    }
}
